//
//  HomeViewController.swift
//  weibo
//
//  Created by 叶子韬韬 on 2017/4/10.
//  Copyright © 2017年 叶子韬韬. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh
class HomeViewController: BaseViewController {

    // MARK:- #注释>懒加载属性
    internal lazy var titleBtn:TitleButton = TitleButton()
    
    // MARK:- #注释>定义一个数组
    internal lazy var viewModelArr : [StatuesViewModel] = [StatuesViewModel]()
    
    
    
    internal lazy var tipLabel : UILabel = UILabel()
    
    internal lazy var popoverAnimaor:PopoverAnimaor = PopoverAnimaor { [weak self](isPresented) in
            self?.titleBtn.isSelected = isPresented
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        visitorView.addRotationAnim()
        // MARK:- #注释>没有登录
        if !isLogin {
            return
        }
        // 设置导航栏
        setupNavigationBar()
        //设置header foot 上拉和下拉刷新
        setupHeaderView()
        setupFootView()
        
        //设置提示label
        setupTipLabel()
        //动态设置cell高度
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200  //估算高度
        
        NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.showNotfic(note:)), name: NSNotification.Name.init(ShowPhotoNotific), object: nil)

    }

}
// MARK:- #注释>设置ui界面
extension HomeViewController{
    // MARK:- #注释> 设置盗汗栏
    internal func setupNavigationBar(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageNormal: "navigationbar_friendattention", imageHighlighted: "navigationbar_friendattention_highlighted")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageNormal: "navigationbar_pop", imageHighlighted: "navigationbar_pop_highlighted")
        
        titleBtn.setTitle("sasasa", for: .normal)
        titleBtn.addTarget(self, action: #selector(HomeViewController.titleClick), for: .touchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    // MARK:- #注释> 下拉刷新
    internal func setupHeaderView() {
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadNewStatuses))
        header?.setTitle("下拉刷新", for:.idle)
        header?.setTitle("释放更新", for: .pulling)
        header?.setTitle("加载中...", for: .refreshing)
        
        tableView.mj_header = header;
        //进入刷新状态
        tableView.mj_header.beginRefreshing()
    }
    
    internal func setupFootView(){
        tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadMoreStatuses))
    }
    
    //提示label
    internal func setupTipLabel(){
        navigationController?.navigationBar.insertSubview(tipLabel, at: 0)
        tipLabel.frame = CGRect.init(x: 0, y: 10, width: UIScreen.main.bounds.size.width, height: 32)
        tipLabel.backgroundColor = UIColor.orange
        tipLabel.textColor = UIColor.white
        tipLabel.textAlignment = .center
        tipLabel.font = UIFont.systemFont(ofSize: 14)
        tipLabel.isHidden = true
    }
    
}
// MARK:- #注释>事件监听
extension HomeViewController{
    
    func titleClick(titleBtn:TitleButton) {
        titleBtn.isSelected = !titleBtn.isSelected
        //print("titleClick")
        
        //创建弹出控制器
        let vc = PopViewController()
        //设置弹出图的位置
        popoverAnimaor.presentedFram = CGRect(x: 100, y: 50, width: 180, height: 250)
        //设置控制器的弹出样式
        vc.modalPresentationStyle = .custom
        //转场代理
        vc.transitioningDelegate = popoverAnimaor
        //自定义转场动画
        present(vc, animated: true, completion: nil)
    }
    
    internal func showNotfic(note:Notification){
        
//        print(note.userInfo ?? "sa")
        
        let indexPath = note.userInfo!["indexPath"] as! NSIndexPath
        let picURLs =  note.userInfo!["picUrls"] as! [URL]
        
        let photoBrowVC :PhotoBrowerViewController = PhotoBrowerViewController(indexPath: indexPath, picURLs: picURLs)
        
        //创建控制器
        present(photoBrowVC, animated: true, completion: nil)
    }
    
}
// MARK:- #注释>请求数据
extension HomeViewController{
    
    
    //加载最新数据
    internal func loadNewStatuses(){
        loadStatues(isNewData: true)
    }
    //加载历史数据
    internal func loadMoreStatuses(){
        loadStatues(isNewData: false)
    }
    
    internal func loadStatues(isNewData:Bool){
        
        //获取since_id
        var since_id = 0
        var max_id = 0
        
        if isNewData {
            since_id = viewModelArr.first?.status?.id ?? 0
        }else{
            max_id = viewModelArr.last?.status?.id ?? 0
            max_id = max_id == 0 ? 0:(max_id-1)
        }
        
        
        NetworkTools.shareInstance.loadStatus(max_id: max_id, since_id: since_id) { (result, error) in
            if error != nil{
                print(error ?? "")
                return
            }
            //先获取可选类型数组  进行校验
            guard let resultArray = result else{
                
                return
            }

            //遍历数组
            var tempArr = [StatuesViewModel]()
            for statusDict in resultArray {
                let staus = Statues(dict: statusDict)
                let viewModel = StatuesViewModel(status: staus)
                //把字典放入数组中
               tempArr.append(viewModel)
            }

            if isNewData {
                //对数组进行处理
                self.viewModelArr = tempArr + self.viewModelArr
            }else{
                self.viewModelArr = self.viewModelArr + tempArr
            }
           
            
            //缓存图片
            self.cacheImages(viewModels: tempArr)

         }
    }
    
    //缓存图片
    internal func cacheImages(viewModels:[StatuesViewModel]){
        //创建group
        let group =  DispatchGroup.init()
        
        for viewModel in viewModels {
            for picUrl in viewModel.picURLs {
               //进去组(线程)
               group.enter()
                
                SDWebImageManager.shared().imageDownloader?.downloadImage(with: picUrl, options: [], progress: nil, completed: { (_, _, _, _) in
                    
                    //离开组（线程）
                    group.leave()
                })
            }
        }
        
        //刷新表格
        group.notify(queue: DispatchQueue.main, work: DispatchWorkItem.init(block: { 
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            //显示tipLabel
           self.showTiplabel(count: viewModels.count)
            
        }))
        
    }
    
    internal func showTiplabel(count:Int){
        self.tipLabel.isHidden = false
        tipLabel.text = count == 0 ? "没有新数据" : "\(count)条微博"
        UIView.animate(withDuration: 1.0, animations: { 
            self.tipLabel.frame.origin.y = 44
        }) { (_) in
            UIView.animate(withDuration: 1.0, delay: 1.0, options: [], animations: { 
                self.tipLabel.frame.origin.y = 10
            }, completion: { (_) in
                self.tipLabel.isHidden = true
            })
        }
    }
    
}
// MARK:- #注释>数据源代理
extension HomeViewController{
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModelArr.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //创建cell
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCellID") as! HomeViewCell
        

        //给cell设置数据
        cell.viewModel = self.viewModelArr[indexPath.row]
        
        return cell
        
    }
}



